package com.ossean;

import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;

import com.ossean.databaseDest.DBDest;
import com.ossean.databaseSource.DBSource;
import com.ossean.model.EddRelations;
import com.ossean.util.TransferProjectsUtil;


@Component
public class TransferProjects {
	Logger logger = Logger.getLogger(this.getClass());
	
	@Resource
	private DBSource dbSource;
	@Resource
	private DBDest dbDest;
	@Qualifier("transferProjectsUtil")
	@Autowired
	private TransferProjectsUtil transferProjectsUtil;
	
	
	private String pointerTableName = "edd_pointers";
	private String sourceTableName = "edd_relations";
	private String targetTableName = "open_source_projects";
	
	private int batchSize = 100;
	
	//读指针
    public int readPointer(String table, String source, String target){
		int pointer = 1;
		//pointer的初始值应该从数据库中读出最小的id
		try {
			pointer = dbSource.getMinId(source);
		} catch (Exception e){
			//表示表中没有数据
			logger.info("No item in this table");
			dbSource.insertPointer(table, source, target, 1);
			return 1;
		}
		
		try {
			pointer = dbSource.getPointer(table, source, target);
		} catch(Exception e) {
			logger.info("No such pointer! Create one");
			dbSource.insertPointer(table, source, target, pointer);
		}
		return pointer;
	}
	
	public void start(){
		while(true){
			int startId = readPointer(pointerTableName, sourceTableName, targetTableName);
			List<EddRelations> eddRelationList = dbSource.getEddRelationList(sourceTableName, startId, batchSize);
			if(eddRelationList.size() == 0){
				try {
					logger.info("没有数据了，休眠10min");
					Thread.sleep(600*1000L);
					continue;
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			for(EddRelations relation:eddRelationList){
				transferProjectsUtil.handleOneRelation(relation);
			}
			
		}
	}
	
	public static void main(String[] args){
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:/applicationContext*.xml");
		TransferProjects Main = applicationContext.getBean(TransferProjects.class);
		Main.start();
	}

}
